package com.katze.common.ws.config;


import com.katze.common.ws.core.MessageChannel;
import com.katze.common.ws.core.MessageDispatcher;
import com.katze.common.ws.core.MessageListener;
import com.katze.common.ws.core.NettyWebSocketServer;
import com.katze.common.ws.handler.JwtAuthHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;


@ConditionalOnBean({MessageChannel.class, JwtAuthHandler.class})
public class WeSocketConfig {

    @Bean
    @ConfigurationProperties("app.ws")
    public WebSocketProperties properties() {
        return new WebSocketProperties();
    }

    @Bean
    public MessageDispatcher webSocketDispatcher(ObjectProvider<MessageChannel> messageHandlers, JwtAuthHandler jwtAuthHandler) {
        MessageDispatcher dispatcher = new MessageDispatcher(jwtAuthHandler);

        // 自动注册所有 MessageHandler 实现
        messageHandlers.stream()
                .forEach(handler -> {
                    MessageListener annotation = handler.getClass().getAnnotation(MessageListener.class);
                    if (annotation != null) {
                        dispatcher.registerHandler(annotation.value(), handler);
                    }
                });
        return dispatcher;
    }


    @Bean(initMethod = "start", destroyMethod = "stop")
    public NettyWebSocketServer webSocketServer(WebSocketProperties properties, MessageDispatcher dispatcher) {
        return new NettyWebSocketServer(properties, dispatcher);
    }
}

